package com.jiabowen.store.service.impl;

import com.jiabowen.store.entity.Address;
import com.jiabowen.store.mapper.AddressMapper;
import com.jiabowen.store.mapper.DistrictMapper;
import com.jiabowen.store.service.IAddressService;
import com.jiabowen.store.service.IDistrictService;
import com.jiabowen.store.service.exception.*;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    //在添加用户的收货地址的业务层依赖于IDistrictService的业务接口
    @Autowired
    private IDistrictService districtService;

    @Value("${user.address.max-count}")
    private Integer maxCount;

    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        //调用收获地址统计的方法
        Integer count = addressMapper.countByUid(uid);
        if (count >= maxCount){
            throw new AddressCountLimitException("用户收货地址超出上限");
        }

        String provinceNameByCode = districtService.getNameByCode(address.getProvinceCode());
        String cityNameByCode = districtService.getNameByCode(address.getCityCode());
        String areaNameByCode = districtService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceNameByCode);
        address.setCityName(cityNameByCode);
        address.setAreaName(areaNameByCode);

        //设置uid isdefault
        address.setUid(uid);
        Integer isdefault = count == 0 ? 1 : 0;//1表示默认，0表示不是默认
        address.setIsDefault(isdefault);
        //补全日志
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

//        address.set

        //插入收货地址的方法
        Integer rows = addressMapper.insert(address);
        if (rows != 1){
            throw new InsertException("插入用户的收货地址产生未知异常");
        }
    }

    @Override
    public List<Address> getAddressByUid(Integer uid) {
        List<Address> list = addressMapper.findByUid(uid);

        for (int i = 0; i < list.size(); i++) {
            Address data = new Address();

            Address address = list.get(i);

            String name = address.getName();
            String addressAddress = address.getAddress();
            String provinceName = address.getProvinceName();
            String cityName = address.getCityName();
            String areaName = address.getAreaName();
            String tag = address.getTag();
            String zip = address.getZip();
            String phone = address.getPhone();
            Integer aid = address.getAid();

            data.setName(name);
            data.setAddress(addressAddress);
            data.setProvinceName(provinceName);
            data.setCityName(cityName);
            data.setAreaName(areaName);
            data.setTag(tag);
            data.setZip(zip);
            data.setPhone(phone);
            data.setAid(aid);

            list.set(i,data);
        }
       /* for (Address address : list) {

            String name = address.getName();
            String addressAddress = address.getAddress();
            String provinceName = address.getProvinceName();
            String cityName = address.getCityName();
            String areaName = address.getAreaName();
            String tag = address.getTag();
            String zip = address.getZip();
            String phone = address.getPhone();

            data.setName(name);
            data.setAddress(addressAddress);
            data.setProvinceName(provinceName);
            data.setCityName(cityName);
            data.setAreaName(areaName);
            data.setTag(tag);
            data.setZip(zip);
            data.setPhone(phone);

            address = data;
        }*/
        return list;
    }

    @Override
    public void setAddressDefault(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);
        if (result == null){
            throw new AddressNotFoundException("收货地址不存在异常");
        }
        //检测当前获取到的收货地址数据的归属
        if (!result.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问异常");
        }
        //先将所有的收货地址设置为非默认
        Integer rows = addressMapper.updateNonDefault(uid);
        if (rows <1){
            throw new UpdateException("更新数据时产生未知异常");
        }
        //将用户选中的收货地址设置为默认收货地址
        rows = addressMapper.updateDefaultByAid(aid, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新数据时产生未知异常");
        }
    }

    @Override
    public void delete(Integer aid, Integer uid, String username) {
        //通过aid查询当前删除地址是否存在
        Address result = addressMapper.findByAid(aid);
        if (result == null){
            throw new AddressNotFoundException("收货地址数据不存在");
        }
        //检测当前获取到的收货地址数据的归属
        if (!result.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问异常");
        }
        //根据aid来删除这条数据
        Integer rows = addressMapper.deleteByAid(aid);
        if (rows != 1){
            throw new DeleteException("删除数据产生未知的异常");
        }

        //通过uid来查询删除后当前用户下的所有地址信息
        Integer count = addressMapper.countByUid(uid);
        //如果结果为0 则终止程序
        if (count == 0){
            return;
        }

        //判断当前删除地址是否为默认地址，如果为非默认地址则直接终止
        if (result.getIsDefault() == 0){
            return;
        }
        //通过uid查询出当前用户所有地址中修改时间最晚的数据，将其设置为默认地址
        Address address = addressMapper.findLastModified(uid);
        rows = addressMapper.updateDefaultByAid(address.getAid(), username, new Date());
        if (rows != 1){
            throw new UpdateException("更新数据时产生未知异常");
        }
    }

    /**
     * 通过cid查询地址表中的数据
     * @param aid
     * @param uid
     * @return
     */
    @Override
    public Address getByAid(Integer aid,Integer uid) {
        Address result = addressMapper.findByAid(aid);
        if (result == null){
            throw new AddressNotFoundException("收货地址不存在异常");
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("数据非法访问异常");
        }
        result.setProvinceCode(null);
        result.setCityCode(null);
        result.setAreaCode(null);
        result.setCreatedUser(null);
        result.setCreatedTime(null);
        result.setModifiedUser(null);
        result.setModifiedTime(null);
        return result;
    }
}
